import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    numberArray: [],//选项
    chooseNum: null,
    value:null,//选择的值
    timeStr: 0,//页面倒计时
    count: 0,//题目数量
    currentIndex: 0, // 当前题目索引
    currentTopic: null, // 当前展示的题目
    decisionContent: '', //决策力内容
    questionAnswer:null,//答案
    title:'',//标题
    questionIndex:0,//当前题型索引
    topicContent:[],//当前题型所有题目
    countdownInterval: null, // 存储 interval ID
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.getTopicData();

    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },
  getTopicData(){
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count,topicContent} = util.getData(questionIndex);
    this.setData({
      count,
      topicContent,
      questionIndex
    })
    this.getCurrentTopicData();
  },
  getCurrentTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {topicContent,currentIndex,count} = this.data;
    // 缓存下一题图片
    let newIndex = currentIndex + 1;
    if(newIndex < count){
      util.preLoadImg(questionIndex,newIndex)
    }
    const preImgs = wx.getStorageSync('preImgs')||[];

    const currentTopic = topicContent[currentIndex];// 当前展示的题目
    let questionContent = JSON.parse(currentTopic.answerSheet).content;// 大图数据
    const questionCountdown = JSON.parse(currentTopic.answerSheet).residenceTime;
    let timeStr = parseInt(questionCountdown, 10) / 1000;
    // 添加 NaN 检查，如果为 NaN 则设置默认值
    if (isNaN(timeStr) || timeStr <= 0) {
      timeStr = 120; // 设置默认倒计时为60秒
    }
    // 将td中的颜色文字替换为带有颜色样式的span标签
    const colorMap = {
      '黄': '#FBEF48', // 黄色
      '红': '#DD1436', // 红色
      '紫': '#7F6C9D', // 紫色
      '绿': '#12A698', // 绿色
      '蓝': '#306DA3'  // 蓝色
    };

    // 为table添加border样式
    questionContent = questionContent.replace(/<table([^>]*)>/g, '<table$1 border="1" cellpadding="0" cellspacing="0">');
    // 匹配整个td内容，然后在其中查找颜色文字
    questionContent = questionContent.replace(/(<p[^>]*>)(.*?)(<\/p>)/g, (match, startTag, content, endTag) => {
      let modifiedContent = content;
      if(modifiedContent.length > 1){
        return startTag + modifiedContent + endTag;
      }
      Object.keys(colorMap).forEach(color => {
        const colorCode = colorMap[color];
        // 在td内容中查找颜色文字并替换
        modifiedContent = modifiedContent.replace(
          new RegExp(`(${color})`, 'g'),
          `<div style="width:25px;height:25px;border-radius:25px;background-color:${colorCode};"></div>`
        );
      });
      return startTag + modifiedContent + endTag;
    });
    questionContent = questionContent.replace(/(<td[^>]*>)(.*?)(<\/td>)/g, (match, startTag, content, endTag) => {
      let modifiedContent = content;
      if(modifiedContent.length > 1){
        return startTag + modifiedContent + endTag;
      }
      Object.keys(colorMap).forEach((color,index) => {
        if(index > 0){
          const colorCode = colorMap[color];
          // 在td内容中查找颜色文字并替换
          modifiedContent = modifiedContent.replace(
            new RegExp(`(${color})`, 'g'),
            `<div style="width:25px;height:25px;border-radius:25px;background-color:${colorCode};"></div>`
          );
        }
      });
      return startTag + modifiedContent + endTag;
    });
  
    // 修改为查找所有 img 标签
    const allImgTags = questionContent.match(/<img[^>]+src="([^">]+)"/g);
    const imgSrcMatches = [];
    const imgSrcs = [];

    if (allImgTags) {
      allImgTags.forEach(tag => {
        const match = tag.match(/<img[^>]+src="([^">]+)"/);
        if (match && match[1]) {
          imgSrcMatches.push(match[0]); // 完整的img标签
          imgSrcs.push(match[1]); // src属性值
        }
      });
    }

    // console.log('所有img标签:', allImgTags);
    // console.log('所有img标签完整匹配:', imgSrcMatches);
    // console.log('所有图片src地址:', imgSrcs);

    // 处理所有图片的完整路径
    let processedContent = questionContent;
    if (imgSrcs && imgSrcs.length > 0) {
      imgSrcs.forEach((src, index) => {
        if (src) {
          let fullImageUrl = ''
          if(src.startsWith("http")){
            fullImageUrl = src
          }else{
            fullImageUrl = util.base_url + src;
          }
          const isIos =  util.checkPlatform()
          // 替换缓存图片
          if(isIos){
            fullImageUrl = preImgs.find(item => item.url===fullImageUrl)?.path??fullImageUrl+'?x-oss-process=image/format,jpg'
          }else{
            fullImageUrl = preImgs.find(item => item.url===fullImageUrl)?.path??fullImageUrl+'?x-oss-process=image/format,webp'
          }
        
          // 替换对应的img标签的src为完整路径
          processedContent = processedContent.replace(
            imgSrcMatches[index], 
            imgSrcMatches[index].replace(src, fullImageUrl)
          );
        }
      });
      
      this.setData({
        decisionContent: processedContent
      });
    } else {
      this.setData({
        decisionContent: questionContent
      });
    }

    // console.log("decisionContent",this.data.decisionContent)
    const numberArray = currentTopic.optionList;//选项
    const questionAnswer = currentTopic.questionAnswer;//答案
    const descArray = JSON.parse(currentTopic.describe); // 得到标题数组
    const title = descArray[0].content;// 标题数据

    let decisionContent = this.data.decisionContent;
    numberArray.forEach((option, index) => {
      if (option.content && option.content.trim() !== '') {
        // 如果 content 不为空，则在 newContent 中添加显示内容的标签
        decisionContent += `<span style="display:block;margin: 10px;">${option.serialNumber}：${option.content}</span>`;
      }
    });

    this.setData({
      currentTopic,
      numberArray,
      questionAnswer,
      title,
      timeStr,
      decisionContent
    }, () => {
      // 数据更新完成后启动倒计时
      this.startCountdown();
      // 记录题目开始时间
      this.setData({
        questionStartTime: new Date().getTime()
      })
    });
  },
   
  // 启动倒计时
  startCountdown() {
    let that = this;
    // 清除已有倒计时
    if (that.data.countdownInterval) {
      clearInterval(that.data.countdownInterval);
    }
    const interval = setInterval(() => {
      if (that.data.timeStr > 0) {
        that.setData({
          timeStr: that.data.timeStr - 1
        });
      } else {
        // 立即清除定时器
        clearInterval(interval);
        that.setData({ countdownInterval: null });
        that.handleTimeout(); // 处理超时逻辑
      }
    }, 1000);
  
    that.setData({ countdownInterval: interval });
  },
  
  // 超时事件
  handleTimeout() {
    wx.showToast({
      title: '已超时',
      icon: 'none',
      duration: 1000
    });
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(true);
    this.setData({
      answerRecords: newAnswerRecords
    })

    setTimeout(() => {
      let {count,currentIndex} = this.data;
      let totalCount = currentIndex + 1;
      this.setData({
        currentIndex: totalCount,
        chooseNum:null,
        value:null
      })
      if (totalCount >= count) {
        let questionNumber = this.data.questionIndex + 1;
        const prevInfo = wx.getStorageSync('questionInfo') || {};
        wx.setStorageSync('questionInfo', {
          ...prevInfo,
          questionNumber
        });
        util.navigateByDesc(questionNumber);//跳转下一题
      } else {
        // 继续下一题
        this.getCurrentTopicData();
      }
    }, 1000);
  },
  onChoose(e) {
    let index = e.currentTarget.dataset.index;
    let {numberArray} = this.data;
    let value = numberArray[index].serialNumber;
    this.setData({
      chooseNum: index,
      value
    })
  },
  // 提交
  onSubmit() {
    let {count,currentIndex,value} = this.data;
    if (!value) return;

    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, value);
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    let totalCount = currentIndex + 1;
    this.setData({
      currentIndex:totalCount,
      chooseNum:null,
      value:null,
      answerRecords: newAnswerRecords
    })
    if (totalCount >= count) {
      let questionNumber = this.data.questionIndex + 1;
      const prevInfo = wx.getStorageSync('questionInfo') || {};
      wx.setStorageSync('questionInfo', {
        ...prevInfo,
        questionNumber
      });
      util.navigateByDesc(questionNumber);//跳转下一题
    } else {
      // 继续下一题
      this.getCurrentTopicData();
    }
  },
   // 处理答题记录
   createAndSaveAnswerRecord(isTimeout = false, userOption = '') {
    const {currentIndex, questionStartTime, topicContent, questionAnswer} = this.data;
    
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);
    
    // 获取当前题目信息
    const currentTopic = topicContent[currentIndex];
    
    // 判断是否正确（超时视为错误）
    let isRight = 0;
    let option = '';
    
    if (!isTimeout) {
      option = userOption;
      isRight = (userOption === questionAnswer) ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: currentTopic.questionId,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.classify,
      stem: currentTopic.stem,
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: currentTopic.questionAnswer,
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },
  onUnload() {
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
     // 页面卸载时确保答题记录已保存
     answerUtil.saveAnswerRecords(this.data.answerRecords);
  },
  onHide() {
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
  }
});